package com.wcs.db;

import com.wcs.domain.Book;
import org.apache.commons.dbutils.QueryRunner;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by lyx on 2017/11/25.
 */
public class MySQLControl {
    //根据自己的数据库地址修改
    private static DataSource ds = DBDataSource.getDataSource("jdbc:mysql://127.0.0.1:3306/test");
    private static QueryRunner qr = new QueryRunner(ds);

    public static void executeUpdate(String sql) throws SQLException {
        qr.update(sql);
    }

    public static void executeInsert(List<Book> data) throws SQLException {
        /*
         * 定义一个Object数组，行列
         * params[i][0]等是对数组赋值，这里用到集合的get方法
         *
         */
        Object[][] params = new Object[data.size()][2];
        for (int i = 0; i < params.length; i++) {
            params[i][0] = data.get(i).getId();
            params[i][1] = data.get(i).getName();
            params[i][2] = data.get(i).getPrice();
        }
        qr.batch("insert into _book (book_id, name, price) values (?,?,?)", params);
        System.out.println("执行数据库完毕！" + "成功插入数据：" + data.size() + "条");
    }
}
